<?php


namespace app\data\service;

use app\data\model\DataNoticePushLog;
use think\admin\Service;

/**
 * 通知服务
 * Class NoticeService
 * @package app\data\service
 */
class NoticeService extends Service
{
    /**
     * 获取用户通知列表
     * @param $userId
     * @param $type
     * @param $page
     * @param $limit
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getUserNoticeList($userId, $type, $page, $limit): \think\Paginator
    {
        $list = DataNoticePushLog::query()->where('user_id', $userId);
        if ($type) {
            $list = $list->where('type', $type);
        }
        return $list->order('id desc')->paginate(['list_rows' => $limit, 'page' => $page]);
    }

    /**
     * 创建通知
     * @param          $userId
     * @param          $title
     * @param          $content
     * @param  string  $type
     */
    public function createNotice($userId, $title, $content, string $type = DataNoticePushLog::NOTICE_TYPE_NEW_POLICY)
    {
        DataNoticePushLog::create([
            'user_id' => $userId,
            'title'   => $title,
            'content' => $content,
            'type'    => $type,
        ]);
    }

    /**
     * 批量创建通知
     * @param  array  $params
     */
    public function batchCreateNotice(array $params)
    {
        DataNoticePushLog::insertAll($params);
    }

    /**
     * 设置已读
     * @param $userId
     * @param $noticeId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setNoticeRead($userId, $noticeId): bool
    {
        /**
         * @var DataNoticePushLog $notice
         */
        $notice = DataNoticePushLog::query()->where('id', $noticeId)->where('user_id', $userId)->find($noticeId);
        return !$notice || $notice->save(['is_read' => 1, 'read_time' => date('Y-m-d H:i:s')]);
    }

    /**
     * 批量设置已读
     * @param $userId
     * @throws \think\db\exception\DbException
     */
    public function batchNoticeRead($userId)
    {
        DataNoticePushLog::query()->where('user_id', $userId)->update(['is_read' => 1]);
    }

    /**
     * @param $userId
     * @param $noticeId
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOne($userId, $noticeId)
    {
        $info = DataNoticePushLog::query()->where('id', $noticeId)->where('user_id', $userId)->find();
        if ($info) {
            $this->setNoticeRead($userId, $noticeId);
        }
        return $info;
    }
}